package com.ctrip.ec.api.admin.controller.tool;

import com.ctrip.ec.api.admin.common.JsonBody;
import com.ctrip.ec.api.admin.model.tool.ColumnModel;
import com.ctrip.ec.api.admin.model.tool.TableColumn;
import com.ctrip.ec.api.admin.model.tool.TableModel;
import com.ctrip.ec.dal.DbAccess;
import com.google.common.base.Strings;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by jiangzy on 2018/8/20.
 */

@Controller
@RequestMapping("tool/table")
public class TableController {
    @GetMapping("list")
    @JsonBody(false)
    @ResponseBody
    public List<TableModel> list(@RequestParam(required = false) String tableName) throws SQLException {


        return tables(tableName);

    }

    @GetMapping(value ="show",produces = "text/html;charset=UTF-8")
    @JsonBody(false)
    @ResponseBody
    public String show(@RequestParam(required = false,value = "tableName") String tbl) throws SQLException {
        List<TableModel> list = this.tables(tbl);
        StringBuilder sb = new StringBuilder();

        sb.append("<html><body><table border='1' style='border-collapse:collapse' >");
        for(TableModel model :list){
            if(model != list.get(0)){
                sb.append("<tr><td colspan='3'>&nbsp;</td></tr>");
            }
            String tableName = model.getTableName();
            if(!Strings.isNullOrEmpty(model.getTableComment())){
                tableName  += "&nbsp;(&nbsp;" + model.getTableComment() + "&nbsp;)";
            }
            sb.append("<tr><td colspan='3' style='font-weight:bold'>" + tableName + "</td></tr>");
            sb.append("<tr style='font-weight:bold'><td>列名</td><td>类型</td><td>描述</td></tr>");
            for(ColumnModel col : model.getColumns()){
                sb.append("<tr>");
                sb.append("<td>" + col.getName() + "</td>");
                sb.append("<td>" + col.getColumnType() + "</td>");
                sb.append("<td>" + col.getComment() + "</td>");
                sb.append("</tr>");
            }

        }
        sb.append("</table></body></html>");

        return sb.toString();

    }



    private  List<TableModel> tables(String tableName) throws SQLException {



        DbAccess db = new DbAccess();
        //String dbName= db.getScalar(String.class,"select database();");
        List<String> tableNames = db.query(String.class, "show tables;");
        List<TableModel>  list = new ArrayList<>();
        for(String  str :tableNames){
            if(!Strings.isNullOrEmpty(tableName)) {
                if(!str.contains(tableName)){
                    continue;
                }
            }
            TableModel model = new TableModel();
            model.setTableName(str);
            String tableComment= db.getScalar(String.class,"\n" +
                    "select table_comment from information_schema.tables where table_schema = (select database()) and table_name=?",str);
            model.setTableComment(tableComment);
            List<ColumnModel> columns = new ArrayList<>();
            List<TableColumn> cList = db.query(TableColumn.class,
                    "select COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,COLUMN_COMMENT from INFORMATION_SCHEMA.Columns where table_name=? and table_schema=(select database())",str);
            for(TableColumn c : cList){
                ColumnModel columnModel = new ColumnModel();
                columnModel.setColumnType(c.getCOLUMNTYPE());
                columnModel.setComment(c.getCOLUMNCOMMENT());
                columnModel.setDateType(c.getDATATYPE());
                columnModel.setName(c.getCOLUMNNAME());
                columns.add(columnModel);
            }
            model.setColumns(columns);
            list.add(model);
        }

        return list;

    }

    @GetMapping(value="gen", produces = "text/html;charset=UTF-8")
    @JsonBody(false)
    @ResponseBody
    public String gen(@RequestParam String tableName) throws SQLException {
        String entity = genEntity(tableName);
        String dao = genDao(tableName);
        String controller = genController(tableName);
        StringBuilder sb = new StringBuilder();



        sb.append("<html><body>");
        sb.append("<div>表名:" + tableName  + "</div>");

        sb.append("<table border='0' style='width:100%'>");
        sb.append("<tr>");
        sb.append("<td style='width:34%'>entity:</td>");
        sb.append("<td style='width:33%'>dao:</td>");
        sb.append("<td style='width:33%'>controller:</td>");
        sb.append("</tr>");
        sb.append("<tr>");
        sb.append("<td style='height:300px;'><textarea style='width:100%;height:100%;'>" + entity + "</textarea></td>");


        sb.append("<td style='height:300px;'><textarea style='width:100%;height:100%;'>" + dao + "</textarea></td>");


        sb.append("<td style='height:300px;'><textarea style='width:100%;height:100%;'>" + controller + "</textarea></td>");
        sb.append("</tr>");
        sb.append("</table></body></html>");
        return sb.toString();
    }

    private String genController(String tableName) throws SQLException {
        String prefix = tableName;
        prefix = prefix.substring(prefix.indexOf('_')+1);

        DbAccess db = new DbAccess();
        String code = db.genController(tableName);

        StringBuilder sb = new StringBuilder();
        sb.append("package " + rootPackage() + "api.admin.controller." + tableName.split("_")[1] + ";\r\n");
        sb.append("import com.ctrip.ec.api.admin.model.query.QueryModel;\r\n");
        sb.append("import com.ctrip.ec.dal.PagerSetting;\r\n");
        sb.append("import "+ rootPackage() + "api.admin.common.RequestContext;\r\n");
        sb.append("import "+ rootPackage() + "biz.dao."+ tableName.split("_")[1] + "." + db.getPascalName(prefix) + "Dao;\r\n");
        sb.append("import " + rootPackage() + "biz.entity." + tableName.split("_")[1] + "." + db.getPascalName(prefix) + "Entity;\r\n");
        sb.append("import org.springframework.beans.factory.annotation.Autowired;\r\n");
        sb.append("import org.springframework.web.bind.annotation.*;\r\n");
        sb.append("import java.sql.SQLException;\r\n");
        sb.append("import java.sql.Timestamp;\r\n");
        sb.append("import java.util.List;\r\n");


        sb.append(code);

        return sb.toString();
    }

    private String genEntity(String tableName) throws SQLException {

        DbAccess db = new DbAccess();

        String code = db.genEntity(tableName, null);

        StringBuilder sbCode = new StringBuilder();

        String rp = rootPackage();



        sbCode.append("package " +rp+ "biz.entity." +tableName.split("_")[1]+ ";\r\n");

        sbCode.append("import " + rp + "dal.DbColumn;\r\n");
        sbCode.append("import " + rp + "dal.DbTable;\r\n");
        sbCode.append("import " + rp + "dal.EntityBase;\r\n");
        sbCode.append("import java.math.BigDecimal;\r\n");
        //import com.ctrip.ec.dal.DbAccess;

        sbCode.append("import com.fasterxml.jackson.annotation.JsonFormat;\r\n");
        sbCode.append("import java.sql.Timestamp;\r\n");

        sbCode.append(code);
        return sbCode.toString();

    }

    private String genDao(String tableName) throws SQLException {

        String prefix = tableName;
        prefix = prefix.substring(prefix.indexOf('_')+1);

        DbAccess db = new DbAccess();
        String code = db.genDao(tableName);

        StringBuilder sb = new StringBuilder();
        sb.append("package "+rootPackage() + "biz.dao." + tableName.split("_")[1] + ";\r\n");
        sb.append("import " + rootPackage() + "dal.DaoBase;\r\n");
        sb.append("import " + rootPackage() + "biz.entity."+ tableName.split("_")[1] +"." + db.getPascalName(prefix) + "Entity;\r\n");
        sb.append("import " + rootPackage() + "dal.DbAccess;\r\n");
        sb.append("import org.springframework.stereotype.Service;\r\n");
        sb.append(code);


        return sb.toString();
    }

    private String rootPackage(){
        String currentPackage = this.getClass().getPackage().getName();
        String[] tmps = currentPackage.split("\\.");
        String packageRoot ="";

        for(int i=0;i<tmps.length-4;i++){
            packageRoot+= tmps[i] + ".";
        }
        return packageRoot;
    }
}
